using System.Collections.Generic;
using System.Collections.ObjectModel;
using InfiniTec.Data;

namespace InfiniTec.Data
{
    public class PropertyDefinitionCollection : Collection<IPropertyDefinition>
    {
        public PropertyDefinitionCollection()
        {
        }


        public PropertyDefinitionCollection(IEnumerable<IPropertyDefinition> values)
        {
            AddRange(values);
        }

        ///<summary>
        ///Inserts an element into the <see cref="T:System.Collections.ObjectModel.Collection`1"></see> at the specified index.
        ///</summary>
        ///
        ///<param name="item">The object to insert. The value can be null for reference types.</param>
        ///<param name="index">The zero-based index at which item should be inserted.</param>
        ///<exception cref="T:System.ArgumentOutOfRangeException">index is less than zero.-or-index is greater than <see cref="P:System.Collections.ObjectModel.Collection`1.Count"></see>.</exception>
        protected override void InsertItem(int index, IPropertyDefinition item)
        {
            if (! Contains(item))
            {
                base.InsertItem(index, item);
            }
        }


        ///<summary>
        ///Replaces the element at the specified index.
        ///</summary>
        ///
        ///<param name="item">The new value for the element at the specified index. The value can be null for reference types.</param>
        ///<param name="index">The zero-based index of the element to replace.</param>
        ///<exception cref="T:System.ArgumentOutOfRangeException">index is less than zero.-or-index is greater than <see cref="P:System.Collections.ObjectModel.Collection`1.Count"></see>.</exception>
        protected override void SetItem(int index, IPropertyDefinition item)
        {
            int i;

            i = IndexOf(item);

            base.SetItem(index, item);

            if (i != -1 &&
                i != index)
            {
                RemoveAt(i);
            }
        }

        public void AddRange(IEnumerable<IPropertyDefinition> values)
        {
            if (values == null)
            {
                return;
            }

            foreach (IPropertyDefinition entry in values)
            {
                Add(entry);
            }

        }

        public ReadOnlyCollection<IPropertyDefinition> AsReadOnly()
        {
            return new ReadOnlyCollection<IPropertyDefinition>(this);
        }

        public string[] ToStringArray()
        {
            List<string> result = new List<string>();

            foreach (IPropertyDefinition definition in this)
            {
                result.Add(definition.Name);
            }
            return result.ToArray();
        }
    }
}